package com.livideo.baseutilslibrary.utils;

import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;

/** AnimationDrawable 添加结束监听等 */
public class AnimDrawableUtils {

    private AnimationDrawable ad;
    private int duration = 0;
    private Handler finishHandler;
    private CallBack callBack;

    public AnimDrawableUtils(AnimationDrawable ad, CallBack callBack) {
        this.ad = ad;
        this.callBack = callBack;
        duration = 0;
        finishHandler = new Handler();
    }

    /**
     * 动画的持续时间
     */
    public int getTotalDuration() {
        if(duration > 0){
            return duration;
        }
        for (int i = 0; i < ad.getNumberOfFrames(); ++i) {
            duration += ad.getDuration(i);
        }
        return duration;
    }

    public void start(){
        if(ad != null){
            ad.start();
            finishHandler.postDelayed(
                    new Runnable() {
                        public void run() {
                            if(callBack != null){
                                callBack.onAnimationEnd();
                                ad.stop();
                                ad.selectDrawable(0);
                            }
                        }
                    }, getTotalDuration());
        }
    }

    public void destory(){
        if (ad != null) {
            ad.stop();
            for (int i = 0; i < ad.getNumberOfFrames(); i++) {
                Drawable frame = ad.getFrame(i);
                if (frame instanceof BitmapDrawable) {
                    ((BitmapDrawable) frame).getBitmap().recycle();
                }
                frame.setCallback(null);
            }
            ad.setCallback(null);
        }
    }

    public interface CallBack {
        void onAnimationEnd();
    }
}
